#include <android/log.h>

extern "C" {

#include "libavutil/opt.h"
#include "libavcodec/avcodec.h"
#include "libavutil/mathematics.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"

}

#include <thread.h>
#include <frame.h>
#include <pthread.h>
#include <ScopeQueue.h>

#define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */
#define STREAM_FRAME_RATE 25 /* 25 images/s */

class Writer: public Thread {
public:
	Writer();
	~Writer();

	bool StartScopeEx(const char* outputFile, int videoWidth,int videoHeight);
	bool StopScope();
	bool WriteVideoFrame(AVPacket* packet, Operation operation);
	bool WriteVideoFrame1(AVFrame* frame, Operation operation);

	bool slapPic(const char *outputFile, AVFrame *frame,
			AVPixelFormat pixelFormat);

protected:
	bool open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st);
	void writeFrame(AVPacket* pkt);
	void record(AVFrame* frame);
	bool write_video_frame(AVStream *st, AVPacket* packet);
	void close_video(AVFormatContext *oc, AVStream *st);

	AVStream* add_stream(AVFormatContext *oc, AVCodec **codec,
			AVCodecID codec_id, AVPixelFormat pixelFormat);

private:
    AVFormatContext* _pInputCtx;
	long _pkgPtsIndex;
	long _pkgDtsIndex;
	long pts;
	long dts;


	private:
		/* audio output */
		uint8_t **src_samples_data;
		int src_samples_linesize;
		int src_nb_samples;

		int max_dst_nb_samples;
		uint8_t **dst_samples_data;
		int dst_samples_linesize;
		int dst_samples_size;

		void *_swrBuffer;
		int _swrBufferSize;

		struct SwrContext *swr_ctx;

		//ת��ʽ
		struct SwsContext* mVideoSwsContext;
		AVFrame *mFrame;
		AVPicture mPicture;


		AVFrame * YUVFrame;
		/* video output */
		//AVFrame *frame;
		AVOutputFormat *_pOutputFmt;
		AVFormatContext *oc;
		AVStream *video_st;
		AVStream *input_stream;
		AVStream *output_stream;
		AVCodec *video_codec;
		int frame_count;
		int videoPtsIndex;
		int picWidth;
		int picHeight;

		bool scopeOn;
		bool requireScopeStop;
		ScopeQueue* mQueue;

		void handleRun(void* ptr);

		float t, tincr, tincr2;
		void initialSampleData(AVCodecContext* c);
	};
